// Logger.cpp
#include "Logger.h"
#include <iostream>
#include <chrono>
#include <iomanip>
#include <sstream>
#include <system_error>
#include <cstring>    // 新增头文件
#include <cerrno>     // 新增头文件
#include <cstdarg>  // 必须包含的头文件
// 其他代码保持不变...
void Logger::init(const std::string& filename, LogLevel minLevel) {
    std::lock_guard<std::mutex> lock(instance().configMutex);
    
    // 配置日志级别
    instance().currentLevel.store(minLevel);
    
    // 初始化文件输出
    if(!filename.empty()) {
        instance().logFile.open(filename, std::ios::app);
        if(!instance().logFile.is_open()) {
            std::cerr << "[INIT] Failed to open log file: " << filename 
                     << " (" << std::strerror(errno) << ")\n"; // 修正命名空间
        }
    }
    
    // 启动工作线程
    instance().worker = std::thread(&Logger::logWorker, &instance());
}

void Logger::log(LogLevel level, const char* format, ...) {
    if(level < instance().currentLevel.load()) return;
    // 格式化消息
    char buffer[1024];
    va_list args;
    va_start(args, format);
    vsnprintf(buffer, sizeof(buffer), format, args);
    va_end(args);
    // 构造完整日志条目
    std::string entry = formatEntry(level, buffer);
    
    // 异步写入队列
    {
        std::lock_guard<std::mutex> lock(instance().logMutex);
        instance().logQueue.push(std::move(entry));
    }
    instance().queueCV.notify_one();
}
// 审计日志专用接口
void Logger::logAudit(const char* format, ...) {
    char buffer[1024];
    va_list args;
    va_start(args, format);
    vsnprintf(buffer, sizeof(buffer), format, args);
    va_end(args);
    std::string entry = formatEntry(LogLevel::SECURITY, buffer);
    entry.insert(entry.find("] ") + 2, "[AUDIT] ");
    // 审计日志同步写入
    std::lock_guard<std::mutex> lock(instance().auditMutex);
    if(instance().auditFile.is_open()) {
        instance().auditFile << entry << std::endl;
    }
    std::cerr << "\033[1;31m" << entry << "\033[0m" << std::endl; // 红色高亮
}
void Logger::logWorker() {
    std::vector<std::string> batch;
    while(!instance().shutdownFlag.load()) {
        {   // 批量获取日志条目
            std::unique_lock<std::mutex> lock(instance().logMutex);
            instance().queueCV.wait_for(lock, std::chrono::seconds(1), 
                [this]{ return !logQueue.empty() || shutdownFlag.load(); });
            
            while(!logQueue.empty() && batch.size() < BATCH_SIZE) {
                batch.push_back(std::move(logQueue.front()));
                logQueue.pop();
            }
        }
        // 批量写入
        if(!batch.empty()) {
            writeBatch(batch);
            batch.clear();
        }
        
        // 每小时检查日志滚动
        auto now = std::chrono::system_clock::now();
        if(now - lastRolloverCheck > std::chrono::hours(1)) {
            checkRollover();
            lastRolloverCheck = now;
        }
    }
    
    // 退出前写入剩余日志
    flushRemaining();
}
// 私有方法实现
std::string Logger::formatEntry(LogLevel level, const char* message) {
    auto now = std::chrono::system_clock::now();
    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
        now.time_since_epoch()) % 1000;
    std::time_t t = std::chrono::system_clock::to_time_t(now);
    
    std::ostringstream oss;
    oss << "[" << std::put_time(std::localtime(&t), "%Y-%m-%d %H:%M:%S")
        << "." << std::setfill('0') << std::setw(3) << ms.count() << "] "
        << "[" << levelToString(level) << "] " 
        << message;
    return oss.str();
}
void Logger::writeBatch(const std::vector<std::string>& batch) {
    std::lock_guard<std::mutex> lock(configMutex);
    
    try {
        // 控制台输出
        for(const auto& entry : batch) {
            std::cerr << entry << std::endl;
        }
        
        // 文件输出
        if(logFile.is_open()) {
            for(const auto& entry : batch) {
                logFile << entry << std::endl;
            }
            logFile.flush();
        }
    } catch(const std::exception& e) {
        std::cerr << "[LOGGER] Write failed: " << e.what() << std::endl;
    }
}
void Logger::checkRollover() {
    std::lock_guard<std::mutex> lock(configMutex);
    
    if(!logFile.is_open()) return;
    
    const auto pos = logFile.tellp();
    if(pos > MAX_LOG_SIZE) {
        try {
            // 关闭当前文件
            logFile.close();
            
            // 重命名旧日志文件
            std::string oldName = filename;
            std::time_t t = std::time(nullptr);
            oldName += "." + std::to_string(t);
            
            if(std::rename(filename.c_str(), oldName.c_str()) != 0) {
                throw std::system_error(errno, std::system_category());
            }
            
            // 创建新日志文件
            logFile.open(filename, std::ios::app);
        } catch(const std::exception& e) {
            std::cerr << "[LOGGER] Rollover failed: " << e.what() << std::endl;
            logFile.open(filename, std::ios::app); // 尝试重新打开
        }
    }
}
// 辅助函数
const char* Logger::levelToString(LogLevel level) noexcept {
    switch(level) {
        case LogLevel::DEBUG:   return "DEBUG";
        case LogLevel::INFO:    return "INFO";
        case LogLevel::WARNING: return "WARN";
        case LogLevel::ERROR:   return "ERROR";
        case LogLevel::SECURITY:return "SECURITY";
        default:               return "UNKNOWN";
    }
}
void Logger::shutdown() {
    instance().shutdownFlag.store(true);
    instance().queueCV.notify_all();
    if(instance().worker.joinable()) {
        instance().worker.join();
    }
    
    std::lock_guard<std::mutex> lock(configMutex);
    if(logFile.is_open()) logFile.close();
    if(auditFile.is_open()) auditFile.close();
}